package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility;
import com.agger.harmonyosthemeseditor.intelligent.*;
import com.agger.harmonyosthemeseditor.userinterface.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.HsvColor;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.data.rdb.ValuesBucket;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.ResourceManager;
import ohos.interwork.utils.PacMapEx;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.os.ProcessManager;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class ThemesBlindBoxSlice extends AbilitySlice
{
    private final int ChooseImage_Background = 1003;
    private final int ChooseImage_Desktop = 1004;
    private final int ChooseImage_Unlock = 1005;
    private final int ChooseThemesBlindBox = 1006;
    public static final int BlindBoxVersion = 1;
    int iNum = 0;
    PixelMap pxm = null;
    TextField textBox_ChineseName = null;
    TextField textBox_InternationalName = null;
    TextField textBox_DesignerName = null;
    TextField textBox_VersionCode = null;
    TextField textBox_BriefInfo = null;
    Component text_ChineseName = null;
    Component text_InternationalName = null;
    Component text_DesignerName = null;
    Component text_VersionCode = null;
    String Dialog_Title = "爱洁羊智慧能力";
    String Dialog_Content_StoragePermissionFailed = "存储功能被禁用，请前往应用管理页，开启主题协作器的存储权限！";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Confirm = "好的";
    String Toast_NoneName = "请录入主题包名称！汉语名称、国际名称，至少填写一项！";
    String Toast_NoneDesigner = "请录入主题包的设计师名称！";
    String Toast_NoneVersion = "请录入主题包的版本号码！";
    String Toast_NoneBriefInfo = "请录入主题包的简单介绍信息！";
    String Toast_NoneDesktops = "请确认所有桌面壁纸图已设置！";
    String Toast_NoneUnlocks = "请确认所有锁屏壁纸图已设置！";
    String Toast_NoneBackgrounds = "请确认所有软件背景图已设置！";
    String Toast_IsProcessing = "主题生成中，请勿进行其它操作！";
    String Toast_Theme_SaveFinish = "主题包已存储至";
    String Toast_Theme_SaveFailed = "存储主题包时出现错误，请确保设备容量充足！";
    String Toast_BlindBox_IsProcessing = "盲盒生成中，请勿进行其它操作！";
    String Toast_BlindBox_SaveFinish = "主题盲盒已存储至";
    String Toast_BlindBox_SaveFailed = "存储主题盲盒时出现错误，请确保设备容量充足！";
    MainThreadEventHandler mainThreadEventHandler;
    PacThemeEventHandler PacThemeEventHandler;
    ScreenEventHandler screenEventHandler;
    PopupDialogDelayEventHandler popupDialogDelayEventHandler;
    Image setBg01 = null;
    Image setBg02 = null;
    Image setBg03 = null;
    Text text_LuckyColor = null;
    Text text_NormalColor = null;
    Text text_WackyColor = null;
    Text text_Desktop01 = null;
    Text text_Desktop02 = null;
    Text text_Desktop03 = null;
    Text text_Unlock01 = null;
    Text text_Unlock02 = null;
    Text text_Unlock03 = null;
    String LuckyColor = "FE5F4F";
    String NormalColor = "609CFF";
    String WackyColor = "FF60FD";
    String Color01 = "FFC6B7";
    String Color02 = "FCE4DE";
    String Color03 = "F4C4B7";
    String Color04 = "FF8362";
    String Color05 = "FFC1B0";
    String Color06 = "996D61";
    String Color07 = "FF8362";
    String Color08 = "FCD8CF";
    String Color09 = "FFF4F2";
    String Color10 = "F4EDEB";
    String Color11 = "EA791A";
    String Color12 = "CCFFF6F4";
    String Color13 = "E17618";
    String Color14 = "FFEEEA";
    String Color15 = "FCDCD4";
    String Color16 = "FFF2EF";
    String Color17 = "FCDED6";
    String Color18 = "FFDCD3";
    String Color19 = "E2907A";
    boolean isProcessing = false;
    boolean isUnpackMode = false;
    boolean isSuccess = false;
    boolean isBlindBoxExist  = false;
    ColorDialog colorDialog = null;
    PopupDialog popupDialog = null;
    Component BuildModeLayout = null;
    Component UnPackingModeLayout = null;
    Text SourceSelector = null;
    Text text_DesiredColor = null;
    TextField textBox_LuckySymbol = null;
    Slider BalanceSlider = null;
    Switch switch_CrazyMode = null;
    Switch switch_IColorEngine = null;
    TextField textBox_UnpackingResults = null;
    String DesiredColor = "FF3030";
    String timeStr = "20220222022202";
    String resultsText = "None";
    private static ThemesBlindBoxSlice Instance = null;
    private static boolean terminateMode = false;

    public ThemesBlindBoxSlice()
    {
        if(Instance==null)
            Instance = this;
        else
        {
            if(!Instance.isProcessing)
            {
                Instance.terminate();
                Instance = this;
            }else
                terminateMode = true;
        }
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
    {
        super.onOrientationChanged(displayOrientation);
        try
        {
            if(!colorDialog.isDestroyed)
            {
                if(!colorDialog.isShowing())
                {
                    colorDialog.setDestroyedListener(null);
                    colorDialog.destory();
                    colorDialog = null;
                    System.gc();
                }
                else
                {
                    colorDialog.setDestroyedListener(null);
                    colorDialog.saveTempColorValue();
                    colorDialog.destory();
                    colorDialog = null;
                    System.gc();
                    recoverDialog_ColorSelector();
                }
            }
        }catch (Exception ex){}
        try
        {
            popupDialog.destroy();
            popupDialog = null;
        }catch (Exception ex){}
        try
        {
            DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
            int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
            text_ChineseName.setLayoutRefreshedListener(null);
            text_InternationalName.setLayoutRefreshedListener(null);
            text_DesignerName.setLayoutRefreshedListener(null);
            text_VersionCode.setLayoutRefreshedListener(null);
            text_ChineseName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_InternationalName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_DesignerName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_VersionCode.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        }catch (Exception e){}
    }

    private class PacThemeEventHandler extends EventHandler
    {
        private PacThemeEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            if(!isUnpackMode)
            {
                isSuccess = false;
                ProcessManager.setThreadPriority(-20);
                String workPath = getCacheDir() + "/ThemesBlindBoxArea_Build";
                File WorkStorage = new File(workPath);
                if(WorkStorage.exists())FileManager.deleteDirectory(workPath,true,false);
                new File(workPath).mkdirs();
                FileManager.copyDir(getCacheDir() + "/ThemesBlindBox",workPath);
                DatabaseManager.Init(workPath);
                DatabaseManager.setString("LuckyColor",LuckyColor);
                DatabaseManager.setString("NormalColor",NormalColor);
                DatabaseManager.setString("WackyColor",WackyColor);
                //用于校验盲盒版本号
                DatabaseManager.setInt("Version",BlindBoxVersion);
                DatabaseManager.Init(getContext());
                FileManager.copyFile(getFilesDir()+"/ThemesTemplate/description.xml",workPath+"/description.xml");
                File xmlFile = new File(workPath+"/description.xml");
                try
                {
                    FileInputStream in = new FileInputStream(xmlFile);
                    byte[] b = new byte[(int) xmlFile.length()];
                    in.read(b);
                    String xmlText = new String(b);
                    in.close();
                    xmlText = xmlText.replaceAll("汉语名称",textBox_ChineseName.getText());
                    xmlText = xmlText.replaceAll("国际名称",textBox_InternationalName.getText());
                    xmlText = xmlText.replaceAll("设计师名",textBox_DesignerName.getText());
                    xmlText = xmlText.replaceAll("版本号码",textBox_VersionCode.getText());
                    xmlText = xmlText.replaceAll("简介信息",textBox_BriefInfo.getText());
                    FileOutputStream out = null;
                    try
                    {
                        out = new FileOutputStream(xmlFile);
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                        writer.write(xmlText);
                        writer.close();
                        out.flush();
                        out.close();
                    }catch(IOException ex){ex.printStackTrace();}
                    finally
                    {
                        try
                        {
                            if (out != null)
                            {
                                out.close();
                            }
                        } catch(IOException e){}
                    }
                }catch(IOException ex) {}
                try
                {
                    if(!new File(getCacheDir()+"/Project_BlindBoxes").exists()) new File(getCacheDir()+"/Project_BlindBoxes").mkdirs();
                    ZipFileManager.zip(workPath,getCacheDir()+"/Project_BlindBoxes/"+textBox_InternationalName.getText()+".tbb");
                    InputStream input = null;
                    try
                    {
                        input = new FileInputStream(getCacheDir()+"/Project_BlindBoxes/"+textBox_InternationalName.getText()+".tbb");
                        ValuesBucket valuesBucket = new ValuesBucket();
                        valuesBucket.putString(AVStorage.Downloads.DISPLAY_NAME, textBox_InternationalName.getText()+".tbb");
                        valuesBucket.putString("relative_path", "Download/ThemesBlindBox/");
                        valuesBucket.putInteger("is_pending", 1);
                        DataAbilityHelper helper = GeneralUtil.createDataAbilityHelper(getContext());
                        int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
                        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                        FileDescriptor fd = helper.openFile(uri, "w");
                        OutputStream output= new FileOutputStream(fd);
                        byte[] buf = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = input.read(buf)) > 0)
                        {
                            output.write(buf, 0, bytesRead);
                        }
                        output.flush();
                        output.close();
                        valuesBucket.clear();
                        valuesBucket.putInteger("is_pending", 0);
                        helper.update(uri, valuesBucket, null);
                        isSuccess = true;
                    }catch (Exception ex) {ex.printStackTrace();}
                    finally {input.close();}
                }catch (Exception e){e.printStackTrace();}
            }else
            {
                isSuccess = false;
                isBlindBoxExist = false;
                resultsText = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_NoneResult,"暂无开盒结果哦~");
                ProcessManager.setThreadPriority(-20);
                if(!new File(getCacheDir()+"/dawnlighti_target_blindbox.tbb").exists())
                {
                    DatabaseManager.Init(getContext());
                    String targetUri = DatabaseManager.getString("ThemesBlindBoxAbility_ThemesBlindBoxUri", "None");
                    if (!targetUri.equals("None"))
                    {
                        DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(getContext());
                        try
                        {
                            InputStream inputStream = null;
                            OutputStream outputStream = null;
                            try
                            {
                                inputStream = new FileInputStream(dataAbilityHelper.openFile(Uri.parse(targetUri), "r"));
                                outputStream = new FileOutputStream(getCacheDir() + "/dawnlighti_target_blindbox.tbb");
                                byte[] buffer = new byte[1024];
                                int length;
                                while ((length = inputStream.read(buffer)) > 0)
                                {
                                    outputStream.write(buffer, 0, length);
                                }
                                outputStream.flush();
                                outputStream.close();
                            } finally
                            {
                                try
                                {
                                    if (outputStream != null)
                                        outputStream.close();
                                    if (inputStream != null)
                                        inputStream.close();
                                } catch (IOException e) {}
                            }
                        } catch (Exception ex) {}
                    }
                }
                if (new File(getCacheDir() + "/dawnlighti_target_blindbox.tbb").exists())
                {
                    isBlindBoxExist = true;
                    int r_Value = DatabaseManager.getInt("BalanceSliderValue",10);
                    int radiusValue = new SecureRandom().nextInt(2)==1?(r_Value+12):(32-r_Value);
                    String outzippath = getCacheDir()+"/blindbox_files";
                    if(new File(outzippath).exists()) FileManager.deleteDirectory(outzippath,true,false);
                    new File(outzippath).mkdirs();
                    if(ZipFileTool.unzip(getCacheDir() + "/dawnlighti_target_blindbox.tbb",outzippath))
                    {
                        DatabaseManager.Init(outzippath);
                        String lColor = DatabaseManager.getString("LuckyColor","FE5F4F");
                        String nColor = DatabaseManager.getString("NormalColor","609CFF");
                        String wColor = DatabaseManager.getString("WackyColor","FF60FD");
                        if(switch_IColorEngine.isChecked())
                        {
                            if(ColorManager.isSimilarColor(Color.getIntColor("#"+DesiredColor),Color.getIntColor("#"+lColor),30f+new SecureRandom().nextInt(31),20f+new SecureRandom().nextInt(21),20f+new SecureRandom().nextInt(21))) Color04 = lColor;
                            else if(ColorManager.isSimilarColor(Color.getIntColor("#"+DesiredColor),Color.getIntColor("#"+nColor),30f+new SecureRandom().nextInt(31),20f+new SecureRandom().nextInt(21),20f+new SecureRandom().nextInt(21))) Color04 = nColor;
                            else if(ColorManager.isSimilarColor(Color.getIntColor("#"+DesiredColor),Color.getIntColor("#"+wColor),30f+new SecureRandom().nextInt(31),20f+new SecureRandom().nextInt(21),20f+new SecureRandom().nextInt(21))) Color04 = wColor;
                            else Color04 = DesiredColor;
                        }else
                        {
                            int _temp = new SecureRandom().nextInt(7);
                            if(_temp<2) Color04 = lColor;
                            else if(_temp<4) Color04 = nColor;
                            else if(_temp<6) Color04 = wColor;
                            else Color04 = DesiredColor;
                        }
                        updateColors();
                        String workPath = getCacheDir() + "/ThemesBlindBoxArea_Unpack";
                        File WorkStorage = new File(workPath);
                        if(WorkStorage.exists())FileManager.deleteDirectory(workPath,true,false);
                        new File(workPath+"/wallpaper").mkdirs();
                        int D_num = 1+new SecureRandom().nextInt(3);
                        FileManager.copyFile(outzippath+"/Desktop0"+D_num+".jpg",workPath+"/wallpaper/home_wallpaper_0.jpg");
                        int U_num = 1+new SecureRandom().nextInt(3);
                        FileManager.copyFile(outzippath+"/Unlock0"+U_num+".jpg",workPath+"/wallpaper/unlock_wallpaper_0.jpg");
                        new File(workPath+"/preview").mkdirs();
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/unlock_slide",workPath+"/unlock");
                        FileManager.copyFile(getFilesDir()+"/ThemesTemplate/preview/preview_icons_0.jpg",workPath+"/preview/preview_icons_0.jpg");
                        PixelMap unlockImage = GeneralUtil.getPixelMapFromFile(new File(outzippath+"/Unlock0"+U_num+".jpg"));
                        if(unlockImage!=null)
                            ImageIntelligent.saveImage(workPath+"/preview/cover.jpg",ImageIntelligent.ResizeImage(unlockImage,1080,2160));
                        FileManager.copyFile(workPath+"/preview/cover.jpg",workPath+"/preview/preview_unlock_0.jpg");
                        FileManager.copyFile(getFilesDir()+"/ThemesTemplate/icons",workPath+"/icons");
                        FileManager.copyFile(outzippath+"/description.xml",workPath+"/description.xml");
                        String packagePath = getCacheDir()+"/blindbox_packages";
                        if(new File(packagePath).exists()) FileManager.deleteDirectory(packagePath,true,false);
                        new File(packagePath).mkdirs();
                        int Bg_num = 1+new SecureRandom().nextInt(3);
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/contacts",packagePath+"/com.android.contacts");
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",packagePath+"/com.android.contacts/framework-res-hwext");
                        FileManager.copyFile(outzippath+"/Background0"+(switch_CrazyMode.isChecked()?String.valueOf(1+new SecureRandom().nextInt(3)):Bg_num)+".jpg",packagePath+"/com.android.contacts/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
                        updateXmlColorValue(packagePath+"/com.android.contacts/framework-res-hwext/theme.xml");
                        updateXmlColorValue(packagePath+"/com.android.contacts/theme.xml");
                        try{ZipFileManager.zip(packagePath+"/com.android.contacts",workPath+"/com.android.contacts");}catch(Exception e){}
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/incallui",packagePath+"/com.android.incallui");
                        try{ZipFileManager.zip(packagePath+"/com.android.incallui",workPath+"/com.android.incallui");}catch(Exception e){}
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/mms",packagePath+"/com.android.mms");
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",packagePath+"/com.android.mms/framework-res-hwext");
                        FileManager.copyFile(outzippath+"/Background0"+(switch_CrazyMode.isChecked()?String.valueOf(1+new SecureRandom().nextInt(3)):Bg_num)+".jpg",packagePath+"/com.android.mms/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
                        FileManager.copyFile(packagePath+"/com.android.contacts/framework-res-hwext/theme.xml",packagePath+"/com.android.mms/framework-res-hwext/theme.xml");
                        updateXmlColorValue(packagePath+"/com.android.mms/theme.xml");
                        try{ZipFileManager.zip(packagePath+"/com.android.mms",workPath+"/com.android.mms");}catch(Exception e){}
                        new File(packagePath+"/com.android.phone").mkdirs();
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",packagePath+"/com.android.phone/framework-res-hwext");
                        FileManager.copyFile(outzippath+"/Background0"+(switch_CrazyMode.isChecked()?String.valueOf(1+new SecureRandom().nextInt(3)):Bg_num)+".jpg",packagePath+"/com.android.phone/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
                        FileManager.copyFile(packagePath+"/com.android.contacts/framework-res-hwext/theme.xml",packagePath+"/com.android.phone/framework-res-hwext/theme.xml");
                        try{ZipFileManager.zip(packagePath+"/com.android.phone",workPath+"/com.android.phone");}catch(Exception e){}
                        if(new File(workPath+"/com.android.phone").exists())FileManager.copyFile(workPath+"/com.android.phone",workPath+"/com.android.server.telecom");
                        else try{ZipFileManager.zip(packagePath+"/com.android.phone",workPath+"/com.android.server.telecom");}catch(Exception e){}
                        if(new File(workPath+"/com.android.phone").exists())FileManager.copyFile(workPath+"/com.android.phone",workPath+"/com.huawei.phone.recorder");
                        else try{ZipFileManager.zip(packagePath+"/com.android.phone",workPath+"/com.huawei.phone.recorder");}catch(Exception e){}
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/mediacontroller",packagePath+"/com.android.systemui");
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",packagePath+"/com.android.systemui/framework-res-hwext");
                        FileManager.copyFile(outzippath+"/Background0"+(switch_CrazyMode.isChecked()?String.valueOf(1+new SecureRandom().nextInt(3)):Bg_num)+".jpg",packagePath+"/com.android.systemui/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
                        FileManager.copyFile(packagePath+"/com.android.contacts/framework-res-hwext/theme.xml",packagePath+"/com.android.systemui/framework-res-hwext/theme.xml");
                        updateXmlColorValue(packagePath+"/com.android.systemui/theme.xml");
                        try{ZipFileManager.zip(packagePath+"/com.android.systemui",workPath+"/com.android.systemui");}catch(Exception e){}
                        if(new File(workPath+"/com.android.systemui").exists())FileManager.copyFile(workPath+"/com.android.systemui",workPath+"/com.huawei.mediacontroller");
                        else try{ZipFileManager.zip(packagePath+"/com.android.systemui",workPath+"/com.huawei.mediacontroller");}catch(Exception e){}
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/launcher",packagePath+"/com.huawei.android.launcher");
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/framework",packagePath+"/com.huawei.android.launcher/framework-res-hwext");
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/card/framework-res-hwext",packagePath+"/com.huawei.android.launcher/framework-res-hwext");
                        FileManager.copyFile(outzippath+"/Background0"+(switch_CrazyMode.isChecked()?String.valueOf(1+new SecureRandom().nextInt(3)):Bg_num)+".jpg",packagePath+"/com.huawei.android.launcher/framework-res-hwext/res/drawable-xxhdpi/background_emui.9.png");
                        FileManager.copyFile(packagePath+"/com.android.contacts/framework-res-hwext/theme.xml",packagePath+"/com.huawei.android.launcher/framework-res-hwext/theme.xml");
                        updateXmlColorValue(packagePath+"/com.huawei.android.launcher/theme.xml");
                        updateXmlRadiusValue(packagePath+"/com.huawei.android.launcher/framework-res-hwext/res/values/dimens.xml",radiusValue);
                        try{ZipFileManager.zip(packagePath+"/com.huawei.android.launcher",workPath+"/com.huawei.android.launcher");}catch(Exception e){}
                        new File(packagePath+"/com.huawei.ohos.famanager").mkdirs();
                        FileManager.copyDir(getFilesDir()+"/ThemesTemplate/card/framework-res-hwext",packagePath+"/com.huawei.ohos.famanager/framework-res-hwext");
                        FileManager.copyFile(packagePath+"/com.huawei.android.launcher/framework-res-hwext/res/values/dimens.xml",packagePath+"/com.huawei.ohos.famanager/framework-res-hwext/res/values/dimens.xml");
                        try{ZipFileManager.zip(packagePath+"/com.huawei.ohos.famanager",workPath+"/com.huawei.ohos.famanager");}catch(Exception e){}
                        if(new File(workPath+"/com.huawei.ohos.famanager").exists())FileManager.copyFile(workPath+"/com.huawei.ohos.famanager",workPath+"/com.huawei.ohos.search");
                        else try{ZipFileManager.zip(packagePath+"/com.huawei.ohos.famanager",workPath+"/com.huawei.ohos.search");}catch(Exception e){}
                        try
                        {
                            timeStr = GeneralUtil.getTimeStr();
                            ZipFileManager.zip(workPath,getCacheDir()+"/"+timeStr+".hwt");
                            InputStream input = null;
                            try
                            {
                                input = new FileInputStream(getCacheDir()+"/"+timeStr+".hwt");
                                ValuesBucket valuesBucket = new ValuesBucket();
                                valuesBucket.putString(AVStorage.Downloads.DISPLAY_NAME, timeStr+".hwt");
                                valuesBucket.putString("relative_path", "Download/ThemesEditor/");
                                valuesBucket.putInteger("is_pending", 1);
                                DataAbilityHelper helper = GeneralUtil.createDataAbilityHelper(getContext());
                                int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
                                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                                FileDescriptor fd = helper.openFile(uri, "w");
                                OutputStream output= new FileOutputStream(fd);
                                byte[] buf = new byte[1024];
                                int bytesRead;
                                while ((bytesRead = input.read(buf)) > 0)
                                {
                                    output.write(buf, 0, bytesRead);
                                }
                                output.flush();
                                output.close();
                                valuesBucket.clear();
                                valuesBucket.putInteger("is_pending", 0);
                                helper.update(uri, valuesBucket, null);
                                GeneralUtil.ThemeInfo themeInfo = GeneralUtil.getThemeInfo(outzippath+"/description.xml");
                                String DesktopResult = "Unknown";
                                if(D_num==1)DesktopResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme01,"一号方案");
                                else if(D_num==2)DesktopResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme02,"二号方案");
                                else if(D_num==3)DesktopResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme03,"三号方案");
                                String UnlockResult = "Unknown";
                                if(U_num==1)UnlockResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme01,"一号方案");
                                else if(U_num==2)UnlockResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme02,"二号方案");
                                else if(U_num==3)UnlockResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme03,"三号方案");
                                String BackgroundResult = "Unknown";
                                if(switch_CrazyMode.isChecked())
                                {
                                    BackgroundResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_CrazyEnabled,"狂暴模式已启用");
                                }else
                                {
                                    if(Bg_num==1)BackgroundResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme01,"一号方案");
                                    else if(Bg_num==2)BackgroundResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme02,"二号方案");
                                    else if(Bg_num==3)BackgroundResult = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_Scheme03,"三号方案");
                                }
                                resultsText = ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_BasicInfo,"盲盒基础信息")+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_IName,"盲盒名称：")+themeInfo.getInternationalName()+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_ISupplier,"供应商：")+themeInfo.getDesignerName()+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_ITime,"开盒时间：")+timeStr+"\r\n\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_SLotteryResults,"本轮中签结果")+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_DyeResult,"染剂：")+"#"+Color04+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_DesktopResult,"桌面：")+DesktopResult+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_UnlockResult,"锁屏：")+UnlockResult+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_BackgroundResult,"背景：")+BackgroundResult+"\r\n"
                                            + ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_CardRadius,"卡片圆角：[值]元量").replaceFirst("[值]",String.valueOf(radiusValue));
                                isSuccess = true;
                            }catch (Exception ex) {ex.printStackTrace();}
                            finally {input.close();}
                        }catch (Exception e){e.printStackTrace();}
                    }
                }
            }
            mainThreadEventHandler.sendEvent(0,0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class PopupDialogDelayEventHandler extends EventHandler
    {
        private PopupDialogDelayEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            try
            {
                popupDialog.destroy();
                popupDialog = null;
            }catch (Exception ex){}
        }
    }

    private class MainThreadEventHandler extends EventHandler
    {
        private MainThreadEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            if(!isUnpackMode)
            {
                if(isSuccess)
                {
                    showShareFaRequest(Toast_BlindBox_SaveFinish+"Download/ThemesBlindBox/"+textBox_InternationalName.getText()+".tbb"+ResourceTool.getString(getContext(),ResourceTable.String_ShareFa_BlindBox,",是否通知附近设备进入盲盒开启页面？（如需使用本能力，请确保目标设备，也已安装当前版本的主题协作器）"));
                }else
                {
                    new GeneralToast(getContext())
                            .setText(Toast_BlindBox_SaveFailed)
                            .show();
                }

            }
            else
            {
                if(!isBlindBoxExist)
                {
                    new GeneralToast(getContext())
                            .setText(ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_FileLost,"盲盒文件已丢失！"))
                            .show();
                }else
                {
                    new GeneralToast(getContext())
                            .setText(isSuccess?(Toast_Theme_SaveFinish+"Download/ThemesEditor/"+timeStr+".hwt"):Toast_Theme_SaveFailed)
                            .show();
                    if(isSuccess)
                        textBox_UnpackingResults.setHint(resultsText);
                }
            }
            isProcessing = false;
            textBox_ChineseName.setEnabled(true);
            textBox_InternationalName.setEnabled(true);
            textBox_DesignerName.setEnabled(true);
            textBox_VersionCode.setEnabled(true);
            textBox_BriefInfo.setEnabled(true);
            textBox_LuckySymbol.setEnabled(true);
            BalanceSlider.setEnabled(true);
            switch_CrazyMode.setEnabled(true);
            switch_IColorEngine.setEnabled(true);
            textBox_ChineseName.setClickedListener(null);
            textBox_InternationalName.setClickedListener(null);
            textBox_DesignerName.setClickedListener(null);
            textBox_VersionCode.setClickedListener(null);
            textBox_BriefInfo.setClickedListener(null);
            textBox_LuckySymbol.setClickedListener(null);
            screenEventHandler.sendSyncEvent(0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class ScreenEventHandler extends EventHandler
    {
        private ScreenEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if(event == null) return;
            if(event.eventId == 0) {try{getWindow().clearFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
            else {try{getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        if(terminateMode)
        {
            terminateMode = false;
            if(Instance!=null)
            {
                if(!Instance.isUnpackMode)
                    new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_BlindBoxProcessing,"盲盒生成中，请勿进行其它操作！")).show();
                else
                    new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_IsProcessing,"主题生成中，请勿进行其它操作！")).show();
                super.onStart(intent);
                super.setUIContent(new DirectionalLayout(this));
                this.terminate();
            }
        }else
        {
            super.onStart(intent);
            super.setUIContent(ResourceTable.Layout_slice_themes_blindbox);
            this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
            this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
            int CurrentColorMode = getColorMode();
            if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
            else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
            this.getWindow().setBackgroundColor(RgbColor.fromArgbInt(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xFEEFF4)));
            ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
            mainThreadEventHandler = new MainThreadEventHandler(EventRunner.current());
            screenEventHandler = new ScreenEventHandler(EventRunner.current());
            GeneralUtil.setWindowToMaxRefreshRate(getWindow());
            GeneralUtil.setWindowSoftInputMode(getWindow(),GeneralUtil.SOFT_INPUT_ADJUST_PAN);
            try
            {
                if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                {
                    if (canRequestPermission("ohos.permission.READ_USER_STORAGE")&&canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
                        requestPermissionsFromUser(new String[] { "ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"} ,2);
                }
            }catch(Exception ex){}
            ResourceManager resManager = getResourceManager();
            try
            {
                Dialog_Title = resManager.getElement(ResourceTable.String_Dialog_Title).getString();
                Dialog_Content_StoragePermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_StoragePermissionFailed).getString();
                Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_Dialog_Button_Cancel).getString();
                Dialog_Button_Confirm = resManager.getElement(ResourceTable.String_Dialog_Button_Confirm).getString();
                Toast_NoneName = resManager.getElement(ResourceTable.String_ThemeToast_NoneName).getString();
                Toast_NoneDesigner = resManager.getElement(ResourceTable.String_ThemeToast_NoneDesigner).getString();
                Toast_NoneVersion = resManager.getElement(ResourceTable.String_ThemeToast_NoneVersion).getString();
                Toast_NoneBriefInfo = resManager.getElement(ResourceTable.String_ThemeToast_NoneBriefInfo).getString();
                Toast_NoneDesktops = resManager.getElement(ResourceTable.String_ThemeToast_NoneDesktops).getString();
                Toast_NoneUnlocks = resManager.getElement(ResourceTable.String_ThemeToast_NoneUnlocks).getString();
                Toast_NoneBackgrounds = resManager.getElement(ResourceTable.String_ThemeToast_NoneBackgrounds).getString();
                Toast_IsProcessing = resManager.getElement(ResourceTable.String_ThemeToast_IsProcessing).getString();
                Toast_Theme_SaveFinish = resManager.getElement(ResourceTable.String_ThemeToast_SaveFinish).getString();
                Toast_Theme_SaveFailed = resManager.getElement(ResourceTable.String_ThemeToast_SaveFailed).getString();
                Toast_BlindBox_IsProcessing = resManager.getElement(ResourceTable.String_ThemeToast_BlindBoxProcessing).getString();
                Toast_BlindBox_SaveFinish = resManager.getElement(ResourceTable.String_ThemeToast_BlindBoxFinish).getString();
                Toast_BlindBox_SaveFailed = resManager.getElement(ResourceTable.String_ThemeToast_BlindBoxFailed).getString();
            }catch (Exception e){}
            isProcessing = false;
            isUnpackMode = false;
            textBox_ChineseName = (TextField) findComponentById(ResourceTable.Id_textBox_chineseName);
            textBox_InternationalName = (TextField) findComponentById(ResourceTable.Id_textBox_internationalName);
            textBox_DesignerName = (TextField) findComponentById(ResourceTable.Id_textBox_designerName);
            textBox_VersionCode = (TextField) findComponentById(ResourceTable.Id_textBox_versionCode);
            textBox_BriefInfo = (TextField) findComponentById(ResourceTable.Id_textBox_briefInfo);
            TextBoxManager.TextBoxForStyle(this,textBox_ChineseName);
            TextBoxManager.TextBoxForStyle(this,textBox_InternationalName);
            TextBoxManager.TextBoxForStyle(this,textBox_DesignerName);
            TextBoxManager.TextBoxForStyle(this,textBox_VersionCode);
            TextBoxManager.TextBoxForStyle(this,textBox_BriefInfo);
            DatabaseManager.Init(this);
            textBox_ChineseName.setText(DatabaseManager.getString("ThemesBlindBox_ChineseName"));
            textBox_InternationalName.setText(DatabaseManager.getString("ThemesBlindBox_InternationalName"));
            textBox_DesignerName.setText(DatabaseManager.getString("ThemesBlindBox_DesignerName"));
            textBox_VersionCode.setText(DatabaseManager.getString("ThemesBlindBox_VersionCode"));
            textBox_BriefInfo.setText(DatabaseManager.getString("ThemesBlindBox_BriefInfo"));
            textBox_ChineseName.addTextObserver((s, i, i1, i2) ->
            {
                try
                {
                    textBox_ChineseName.setText(TextManager.removeSpecificCharArray(textBox_ChineseName.getText()));
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("ThemesBlindBox_ChineseName",textBox_ChineseName.getText());
                }
                catch (Exception e){}
            });
            textBox_InternationalName.addTextObserver((s, i, i1, i2) ->
            {
                try
                {
                    textBox_InternationalName.setText(TextManager.removeSpecificCharArray(textBox_InternationalName.getText()));
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("ThemesBlindBox_InternationalName",textBox_InternationalName.getText());
                }
                catch (Exception e){}
            });
            textBox_DesignerName.addTextObserver((s, i, i1, i2) ->
            {
                try
                {
                    textBox_DesignerName.setText(TextManager.removeSpecificCharArray(textBox_DesignerName.getText()));
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("ThemesBlindBox_DesignerName",textBox_DesignerName.getText());
                }
                catch (Exception e){}
            });
            textBox_VersionCode.addTextObserver((s, i, i1, i2) ->
            {
                try
                {
                    String VersionCodeText = "";
                    char[] texts = textBox_VersionCode.getText().toCharArray();
                    char last = '?';
                    for(int o=0;o<texts.length;o++)
                    {
                        if(TextManager.isNumChar(texts[o]))
                        {
                            if(texts[o]!=last||texts[o]!='.')
                            {
                                VersionCodeText += texts[o];
                                last = texts[o];
                            }
                        }
                    }
                    if(VersionCodeText.startsWith("."))
                    {
                        VersionCodeText = "12"+VersionCodeText;
                    }else if(VersionCodeText.startsWith("0"))
                    {
                        VersionCodeText = "12";
                    }else if(VersionCodeText.startsWith("0.")||VersionCodeText.startsWith("1.")||VersionCodeText.startsWith("2.")||VersionCodeText.startsWith("3.")||VersionCodeText.startsWith("4.")||VersionCodeText.startsWith("5.")||VersionCodeText.startsWith("6.")||VersionCodeText.startsWith("7.")||VersionCodeText.startsWith("8.")||VersionCodeText.startsWith("9.")||VersionCodeText.startsWith("10.")||VersionCodeText.startsWith("11."))
                    {
                        VersionCodeText = "12"+VersionCodeText.substring(VersionCodeText.indexOf('.'));
                    }
                    textBox_VersionCode.setText(VersionCodeText);
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("ThemesBlindBox_VersionCode",VersionCodeText);
                }
                catch (Exception e){}
            });
            textBox_BriefInfo.addTextObserver((s, i, i1, i2) ->
            {
                try
                {
                    textBox_BriefInfo.setText(TextManager.removeSpecificCharArray(textBox_BriefInfo.getText()));
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("ThemesBlindBox_BriefInfo",textBox_BriefInfo.getText());
                }
                catch (Exception e){}
            });
            text_ChineseName = findComponentById(ResourceTable.Id_text_chineseName);
            text_InternationalName = findComponentById(ResourceTable.Id_text_internationalName);
            text_DesignerName = findComponentById(ResourceTable.Id_text_designerName);
            text_VersionCode = findComponentById(ResourceTable.Id_text_versionCode);
            DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
            int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
            text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            DatabaseManager.Init(this);
            LuckyColor = DatabaseManager.getString("ThemesBlindBox_LuckyColor","FE5F4F");
            NormalColor = DatabaseManager.getString("ThemesBlindBox_NormalColor","609CFF");
            WackyColor = DatabaseManager.getString("ThemesBlindBox_WackyColor","FF60FD");
            text_LuckyColor = (Text) findComponentById(ResourceTable.Id_colorBox_luckyColor);
            text_NormalColor = (Text) findComponentById(ResourceTable.Id_colorBox_normalColor);
            text_WackyColor = (Text) findComponentById(ResourceTable.Id_colorBox_wackyColor);
            text_LuckyColor.setText("#"+LuckyColor);
            text_NormalColor.setText("#"+NormalColor);
            text_WackyColor.setText("#"+WackyColor);
            text_LuckyColor.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    iNum = 1;
                    if(colorDialog==null)
                        showDialog_ColorSelector();
                    else
                    {
                        if(!colorDialog.isDestroyed)
                        {
                            colorDialog.setDestroyedListener(null);
                            colorDialog.destory();
                        }
                        colorDialog = null;
                        System.gc();
                        showDialog_ColorSelector();
                    }
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_NormalColor.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    iNum = 2;
                    if(colorDialog==null)
                        showDialog_ColorSelector();
                    else
                    {
                        if(!colorDialog.isDestroyed)
                        {
                            colorDialog.setDestroyedListener(null);
                            colorDialog.destory();
                        }
                        colorDialog = null;
                        System.gc();
                        showDialog_ColorSelector();
                    }
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_WackyColor.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    iNum = 3;
                    if(colorDialog==null)
                        showDialog_ColorSelector();
                    else
                    {
                        if(!colorDialog.isDestroyed)
                        {
                            colorDialog.setDestroyedListener(null);
                            colorDialog.destory();
                        }
                        colorDialog = null;
                        System.gc();
                        showDialog_ColorSelector();
                    }
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_Desktop01 = (Text) findComponentById(ResourceTable.Id_selector_desktop01);
            text_Desktop02 = (Text) findComponentById(ResourceTable.Id_selector_desktop02);
            text_Desktop03 = (Text) findComponentById(ResourceTable.Id_selector_desktop03);
            text_Desktop01.setText("Desktop.jpg");
            text_Desktop02.setText("Desktop.jpg");
            text_Desktop03.setText("Desktop.jpg");
            text_Desktop01.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Desktop,1);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_Desktop02.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Desktop,2);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_Desktop03.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Desktop,3);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_Unlock01 = (Text) findComponentById(ResourceTable.Id_selector_unlock01);
            text_Unlock02 = (Text) findComponentById(ResourceTable.Id_selector_unlock02);
            text_Unlock03 = (Text) findComponentById(ResourceTable.Id_selector_unlock03);
            text_Unlock01.setText("Unlock.jpg");
            text_Unlock02.setText("Unlock.jpg");
            text_Unlock03.setText("Unlock.jpg");
            text_Unlock01.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Unlock,1);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_Unlock02.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Unlock,2);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            text_Unlock03.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Unlock,3);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            pxm = GeneralUtil.getPixelMapFromResource(this,ResourceTable.Media_symbol_add);
            setBg01 = (Image) findComponentById(ResourceTable.Id_setBg01);
            setBg02 = (Image) findComponentById(ResourceTable.Id_setBg02);
            setBg03 = (Image) findComponentById(ResourceTable.Id_setBg03);
            setBg01.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
            setBg02.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
            setBg03.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
            setBg01.setPixelMap(pxm);
            setBg02.setPixelMap(pxm);
            setBg03.setPixelMap(pxm);
            setBg01.setCornerRadius(12f*displayAttributes.scalDensity);
            setBg02.setCornerRadius(12f*displayAttributes.scalDensity);
            setBg03.setCornerRadius(12f*displayAttributes.scalDensity);
            setBg01.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Background,1);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            setBg02.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Background,2);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            setBg03.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectPic(ChooseImage_Background,3);
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
            });
            Button Button_StartProcess= (Button) findComponentById(ResourceTable.Id_Button_StartProcess);
            int spacingHorizontal = (int) ResourceTool.getFloat(this, ResourceTable.Float_spacing_ui_button, 0);
            Button_StartProcess.setBackground(new GeneralButtonElement(this, GeneralButtonElement.TYPE_UI_Button));
            Button_StartProcess.setTextColor(new Color(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_button_text_accent, 0xFFFFFF)));
            Button_StartProcess.setMultipleLine(false);
            Button_StartProcess.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
            Button_StartProcess.setPaddingLeft(spacingHorizontal);
            Button_StartProcess.setPaddingRight(spacingHorizontal);
            SourceSelector = (Text) findComponentById(ResourceTable.Id_BlindBox_SourceSelector);
            SourceSelector.setText("Default.tbb");
            SourceSelector.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    try
                    {
                        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else
                            selectBlindBox();
                    }catch(Exception ex){}
                }else
                    new GeneralToast(this).setText(Toast_IsProcessing).show();
            });
            text_DesiredColor = (Text) findComponentById(ResourceTable.Id_colorBox_desiredColor);
            DatabaseManager.Init(this);
            DesiredColor = DatabaseManager.getString("ThemesBlindBox_DesiredColor","FF3030");
            text_DesiredColor.setText("#"+DesiredColor);
            text_DesiredColor.setClickedListener(c ->
            {
                if(!isProcessing)
                {
                    iNum = -1;
                    if(colorDialog==null)
                        showDialog_ColorSelector();
                    else
                    {
                        if(!colorDialog.isDestroyed)
                        {
                            colorDialog.setDestroyedListener(null);
                            colorDialog.destory();
                        }
                        colorDialog = null;
                        System.gc();
                        showDialog_ColorSelector();
                    }
                }else
                    new GeneralToast(this).setText(Toast_IsProcessing).show();
            });
            textBox_LuckySymbol = (TextField) findComponentById(ResourceTable.Id_textBox_luckySymbol);
            TextBoxManager.TextBoxForStyle(this,textBox_LuckySymbol);
            DatabaseManager.Init(this);
            textBox_LuckySymbol.setText(DatabaseManager.getString("ThemesBlindBox_LuckySymbol"));
            textBox_LuckySymbol.addTextObserver((s, i, i1, i2) ->
            {
                try
                {
                    String str = textBox_LuckySymbol.getText();
                    if(str.length()>6)
                        str = str.substring(0,6);
                    textBox_LuckySymbol.setText(str);
                    DatabaseManager.Init(this);
                    DatabaseManager.setString("ThemesBlindBox_LuckySymbol",str);
                }
                catch (Exception e){}
            });
            BalanceSlider = (Slider) findComponentById(ResourceTable.Id_slider_balanceStrength);
            BalanceSlider.setMinValue(0);
            BalanceSlider.setMaxValue(20);
            DatabaseManager.Init(getContext());
            int R_value = DatabaseManager.getInt("BalanceSliderValue",10);
            BalanceSlider.setProgressValue(R_value);
            BalanceSlider.setStep(1);
            BalanceSlider.setValueChangedListener(new Slider.ValueChangedListener()
            {
                @Override
                public void onProgressUpdated(Slider slider, int i, boolean b)
                {
                    DatabaseManager.Init(getContext());
                    DatabaseManager.setInt("BalanceSliderValue",i);
                }
                @Override
                public void onTouchStart(Slider slider) {}
                @Override
                public void onTouchEnd(Slider slider) {}
            });
            switch_CrazyMode = (Switch) findComponentById(ResourceTable.Id_Settings_CrazyMode);
            switch_IColorEngine = (Switch) findComponentById(ResourceTable.Id_Settings_IColorEngine);
            DatabaseManager.Init(this);
            switch_CrazyMode.setChecked(DatabaseManager.getString("ThemesBlindBox_EnableCrazyMode","No").equals("Yes"));
            switch_IColorEngine.setChecked(DatabaseManager.getString("ThemesBlindBox_EnableIColorEngine","Yes").equals("Yes"));
            switch_CrazyMode.setCheckedStateChangedListener((button,isChecked)->
            {
                DatabaseManager.Init(this);
                DatabaseManager.setString("ThemesBlindBox_EnableCrazyMode",isChecked?"Yes":"No");
            });
            switch_IColorEngine.setCheckedStateChangedListener((button,isChecked)->
            {
                DatabaseManager.Init(this);
                DatabaseManager.setString("ThemesBlindBox_EnableIColorEngine",isChecked?"Yes":"No");
            });
            textBox_UnpackingResults = (TextField) findComponentById(ResourceTable.Id_textBox_ShowResult);
            textBox_UnpackingResults.setHint(ResourceTool.getString(this,ResourceTable.String_BlindBox_NoneResult,"暂无开盒结果哦~"));
            Button_StartProcess.setClickedListener(c->
            {
                if(!isUnpackMode)
                {
                    if(!isProcessing)
                    {
                        if((setBg01.getPixelMap()!=null&&setBg01.getPixelMap()!=pxm)&&(setBg02.getPixelMap()!=null&&setBg02.getPixelMap()!=pxm)&&(setBg03.getPixelMap()!=null&&setBg03.getPixelMap()!=pxm))
                        {
                            if(verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                                showPermissionRequest();
                            else if(text_Desktop01.getText().equals("Desktop.jpg")||!new File(getCacheDir() + "/ThemesBlindBox/Desktop01.jpg").exists())
                            {
                                text_Desktop01.setText("Desktop.jpg");
                                new GeneralToast(this).setText(Toast_NoneDesktops).show();
                            }
                            else if(text_Desktop02.getText().equals("Desktop.jpg")||!new File(getCacheDir() + "/ThemesBlindBox/Desktop02.jpg").exists())
                            {
                                text_Desktop02.setText("Desktop.jpg");
                                new GeneralToast(this).setText(Toast_NoneDesktops).show();
                            }
                            else if(text_Desktop03.getText().equals("Desktop.jpg")||!new File(getCacheDir() + "/ThemesBlindBox/Desktop03.jpg").exists())
                            {
                                text_Desktop03.setText("Desktop.jpg");
                                new GeneralToast(this).setText(Toast_NoneDesktops).show();
                            }
                            else if(text_Unlock01.getText().equals("Unlock.jpg")||!new File(getCacheDir() + "/ThemesBlindBox/Unlock01.jpg").exists())
                            {
                                text_Unlock01.setText("Unlock.jpg");
                                new GeneralToast(this).setText(Toast_NoneUnlocks).show();
                            }
                            else if(text_Unlock02.getText().equals("Unlock.jpg")||!new File(getCacheDir() + "/ThemesBlindBox/Unlock02.jpg").exists())
                            {
                                text_Unlock02.setText("Unlock.jpg");
                                new GeneralToast(this).setText(Toast_NoneUnlocks).show();
                            }
                            else if(text_Unlock03.getText().equals("Unlock.jpg")||!new File(getCacheDir() + "/ThemesBlindBox/Unlock03.jpg").exists())
                            {
                                text_Unlock03.setText("Unlock.jpg");
                                new GeneralToast(this).setText(Toast_NoneUnlocks).show();
                            }
                            else if(textBox_ChineseName.getText().equals("")&&textBox_InternationalName.getText().equals(""))
                                new GeneralToast(this).setText(Toast_NoneName).show();
                            else if(textBox_DesignerName.getText().equals(""))
                                new GeneralToast(this).setText(Toast_NoneDesigner).show();
                            else if(textBox_VersionCode.getText().equals(""))
                                new GeneralToast(this).setText(Toast_NoneVersion).show();
                            else if(textBox_BriefInfo.getText().equals(""))
                                new GeneralToast(this).setText(Toast_NoneBriefInfo).show();
                            else if(!PreloadServiceAbility.isSuccess)
                                new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_EnvironmentNotReady,"智慧意识未就绪，请确保必要支持库已成功部署！")).show();
                            else
                            {
                                isProcessing = true;
                                textBox_ChineseName.setEnabled(false);
                                textBox_InternationalName.setEnabled(false);
                                textBox_DesignerName.setEnabled(false);
                                textBox_VersionCode.setEnabled(false);
                                textBox_BriefInfo.setEnabled(false);
                                textBox_LuckySymbol.setEnabled(false);
                                BalanceSlider.setEnabled(false);
                                switch_CrazyMode.setEnabled(false);
                                switch_IColorEngine.setEnabled(false);
                                textBox_ChineseName.setClickedListener(i->new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show());
                                textBox_InternationalName.setClickedListener(i->new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show());
                                textBox_DesignerName.setClickedListener(i->new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show());
                                textBox_VersionCode.setClickedListener(i->new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show());
                                textBox_BriefInfo.setClickedListener(i->new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show());
                                if(textBox_ChineseName.getText().equals("")) textBox_ChineseName.setText(textBox_InternationalName.getText());
                                else if(textBox_InternationalName.getText().equals("")) textBox_InternationalName.setText(textBox_ChineseName.getText());
                                String ThemeVersion = textBox_VersionCode.getText();
                                if(!ThemeVersion.contains("."))
                                {
                                    ThemeVersion += ".0";
                                }else if(ThemeVersion.endsWith("."))
                                {
                                    ThemeVersion += "0";
                                }
                                if(ThemeVersion.startsWith("0.")||ThemeVersion.startsWith("1.")||ThemeVersion.startsWith("2.")||ThemeVersion.startsWith("3.")||ThemeVersion.startsWith("4.")||ThemeVersion.startsWith("5.")||ThemeVersion.startsWith("6.")||ThemeVersion.startsWith("7.")||ThemeVersion.startsWith("8.")||ThemeVersion.startsWith("9.")||ThemeVersion.startsWith("10.")||ThemeVersion.startsWith("11."))
                                {
                                    ThemeVersion = "12"+ThemeVersion.substring(ThemeVersion.indexOf('.'));
                                }
                                textBox_VersionCode.setText(ThemeVersion);
                                screenEventHandler.sendSyncEvent(1,EventHandler.Priority.IMMEDIATE);
                                PacThemeEventHandler.sendEvent(0, 0, EventHandler.Priority.IMMEDIATE);
                            }
                        }else
                            new GeneralToast(this).setText(Toast_NoneBackgrounds).show();
                    }else
                        new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
                }else
                {
                    if(!isProcessing)
                    {
                        if(verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                            showPermissionRequest();
                        else if(SourceSelector.getText().equals("Default.tbb")||!new File(getCacheDir()+"/dawnlighti_target_blindbox.tbb").exists())
                        {
                            SourceSelector.setText("Default.tbb");
                            new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_BlindBox_NoneSource,"请选取主题盲盒！")).show();
                        }
                        else if(textBox_LuckySymbol.getText().equals(""))
                            new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_BlindBox_NoneLuckySymbol,"请录入惊喜字符！")).show();
                        else if(!PreloadServiceAbility.isSuccess)
                            new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_EnvironmentNotReady,"智慧意识未就绪，请确保必要支持库已成功部署！")).show();
                        else
                        {
                            isProcessing = true;
                            textBox_ChineseName.setEnabled(false);
                            textBox_InternationalName.setEnabled(false);
                            textBox_DesignerName.setEnabled(false);
                            textBox_VersionCode.setEnabled(false);
                            textBox_BriefInfo.setEnabled(false);
                            textBox_LuckySymbol.setEnabled(false);
                            BalanceSlider.setEnabled(false);
                            switch_CrazyMode.setEnabled(false);
                            switch_IColorEngine.setEnabled(false);
                            textBox_LuckySymbol.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                            screenEventHandler.sendSyncEvent(1,EventHandler.Priority.IMMEDIATE);
                            PacThemeEventHandler.sendEvent(0, 0, EventHandler.Priority.IMMEDIATE);
                        }
                    }else
                    {
                        new GeneralToast(this).setText(Toast_IsProcessing).show();
                    }
                }
            });
            BuildModeLayout = findComponentById(ResourceTable.Id_scrollview_build);
            UnPackingModeLayout = findComponentById(ResourceTable.Id_scrollview_unpacking);
            Component Actionbar_Switch_Item_Pressed = findComponentById(ResourceTable.Id_actionBar_Switch_Pressed_Item);
            Component Actionbar_Switch_Button = findComponentById(ResourceTable.Id_actionBar_Switch);
            Actionbar_Switch_Button.setClickedListener(c->onChangeMode());
            Actionbar_Switch_Button.setLongClickedListener(c->showDialog_Popup_SwitchMode(c));
            Actionbar_Switch_Button.setComponentStateChangedListener((c,i) ->
            {
                if(i == 18432)
                    Actionbar_Switch_Item_Pressed.setVisibility(Component.VISIBLE);
                else
                    Actionbar_Switch_Item_Pressed.setVisibility(Component.INVISIBLE);
            });
            Component Actionbar_Back_Item_Pressed = findComponentById(ResourceTable.Id_actionBar_Back_Pressed_Item);
            Component Actionbar_Back_Button = findComponentById(ResourceTable.Id_actionBar_Back);
            Actionbar_Back_Button.setClickedListener(c->onBackPressed());
            Actionbar_Back_Button.setComponentStateChangedListener((c,i) ->
            {
                if(i == 18432)
                    Actionbar_Back_Item_Pressed.setVisibility(Component.VISIBLE);
                else
                    Actionbar_Back_Item_Pressed.setVisibility(Component.INVISIBLE);
            });
            DatabaseManager.Init(this);
            String Ability_QuitBySelf = DatabaseManager.getString("ThemesBlindBoxAbility_QuitBySelf","No");
            if(!Ability_QuitBySelf.equals("Yes"))
            {
                for(int i=1;i<=3;i++)
                {
                    File DesktopFile = new File(getCacheDir() + "/ThemesBlindBox/Desktop0"+i+".jpg");
                    if(!DesktopFile.exists())
                    {
                        String UriString = DatabaseManager.getString("ThemesBlindBoxAbility_ImageUri_Desktop0"+i,"None");
                        if(!UriString.equals("None"))
                        {
                            Uri uri_rec =Uri.parse(UriString);
                            PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                            if(pixelMap_rec != null)
                            {
                                ImageIntelligent.saveImage(getCacheDir() + "/ThemesBlindBox/Desktop0"+i+".jpg",pixelMap_rec);
                                if(DesktopFile.exists())
                                {
                                    if(i==1)
                                        text_Desktop01.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                                    else if(i==2)
                                        text_Desktop02.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                                    else if(i==3)
                                        text_Desktop03.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                                }
                            }
                        }
                    }else
                    {
                        if(i==1)
                            text_Desktop01.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(i==2)
                            text_Desktop02.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(i==3)
                            text_Desktop03.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                    File UnlockFile = new File(getCacheDir() + "/ThemesBlindBox/Unlock0"+i+".jpg");
                    if(!UnlockFile.exists())
                    {
                        String UriString = DatabaseManager.getString("ThemesBlindBoxAbility_ImageUri_Unlock0"+i,"None");
                        if(!UriString.equals("None"))
                        {
                            Uri uri_rec =Uri.parse(UriString);
                            PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                            if(pixelMap_rec != null)
                            {
                                ImageIntelligent.saveImage(getCacheDir() + "/ThemesBlindBox/Unlock0"+i+".jpg",pixelMap_rec);
                                if(UnlockFile.exists())
                                {
                                    if(i==1)
                                        text_Unlock01.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                                    else if(i==2)
                                        text_Unlock02.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                                    else if(i==3)
                                        text_Unlock03.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                                }
                            }
                        }
                    }else
                    {
                        if(i==1)
                            text_Unlock01.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(i==2)
                            text_Unlock02.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(i==3)
                            text_Unlock03.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                    File BgImageFile = new File(getCacheDir() + "/ThemesBlindBox/Background0"+i+".jpg");
                    if(BgImageFile.exists())
                    {
                        PixelMap pixelMap_rec = GeneralUtil.getPixelMapFromFile(BgImageFile);
                        if(pixelMap_rec != null)
                        {
                            if(i==1)
                            {
                                setBg01.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                setBg01.setPixelMap(pixelMap_rec);
                            }
                            else if(i==2)
                            {
                                setBg02.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                setBg02.setPixelMap(pixelMap_rec);
                            }
                            else if(i==3)
                            {
                                setBg03.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                setBg03.setPixelMap(pixelMap_rec);
                            }
                        }
                    }
                    else
                    {
                        String UriString = DatabaseManager.getString("ThemesBlindBoxAbility_ImageUri_Background0"+i,"None");
                        if(!UriString.equals("None"))
                        {
                            Uri uri_rec =Uri.parse(UriString);
                            PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                            if(pixelMap_rec != null)
                            {
                                ImageIntelligent.saveImage(getCacheDir() + "/ThemesBlindBox/Background0"+i+".jpg",pixelMap_rec);
                                if(i==1)
                                {
                                    setBg01.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                    setBg01.setPixelMap(pixelMap_rec);
                                }
                                else if(i==2)
                                {
                                    setBg02.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                    setBg02.setPixelMap(pixelMap_rec);
                                }
                                else if(i==3)
                                {
                                    setBg03.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                    setBg03.setPixelMap(pixelMap_rec);
                                }
                            }
                        }
                    }
                }
            }
            DatabaseManager.Init(this);
            if(!DatabaseManager.getString("ThemesBlindBox_ModeValue","Build").equals("Build"))
            {
                ((Text)findComponentById(ResourceTable.Id_BlindBox_title)).setText(ResourceTool.getString(this,ResourceTable.String_BlindBox_Title_UnPacMode,"开启盲盒"));
                UnPackingModeLayout.setVisibility(Component.VISIBLE);
                BuildModeLayout.setVisibility(Component.HIDE);
                isUnpackMode = true;
            }else
            {
                ((Text)findComponentById(ResourceTable.Id_BlindBox_title)).setText(ResourceTool.getString(this,ResourceTable.String_BlindBox_Title_BuildMode,"制作盲盒"));
                BuildModeLayout.setVisibility(Component.VISIBLE);
                UnPackingModeLayout.setVisibility(Component.HIDE);
            }
            DatabaseManager.setString("ThemesBlindBoxAbility_QuitBySelf","No");
            PacThemeEventHandler = new PacThemeEventHandler(EventRunner.create(true));
            popupDialogDelayEventHandler = new PopupDialogDelayEventHandler(EventRunner.create(true));
        }
    }

    @Override
    public void onBackPressed()
    {
        if(!isProcessing)
        {
            DatabaseManager.Init(this);
            DatabaseManager.setString("LastAbilityName","None");
            DatabaseManager.setString("ThemesBlindBoxAbility_QuitBySelf","Yes");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Background01", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Background02", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Background03", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Desktop01", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Desktop02", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Desktop03", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Unlock01", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Unlock02", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Unlock03", "None");
            DatabaseManager.setString("ThemesBlindBoxAbility_VideoUri", "None");
            DatabaseManager.setString("ThemesBlindBox_ModeValue","Build");
            try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
            ThemesEditorAbility.isMainSceneSlice = true;
            try{setBg01.release();}catch(Exception e){}
            try{setBg02.release();}catch(Exception e){}
            try{setBg03.release();}catch(Exception e){}
            try{pxm.release();}catch(Exception e){}
            try{textBox_ChineseName.release();}catch(Exception e){}
            try{textBox_InternationalName.release();}catch(Exception e){}
            try{textBox_DesignerName.release();}catch(Exception e){}
            try{textBox_VersionCode.release();}catch(Exception e){}
            try{textBox_BriefInfo.release();}catch(Exception e){}
            try{text_ChineseName.release();}catch(Exception e){}
            try{text_InternationalName.release();}catch(Exception e){}
            try{text_DesignerName.release();}catch(Exception e){}
            try{text_VersionCode.release();}catch(Exception e){}
            try{text_LuckyColor.release();}catch(Exception e){}
            try{text_NormalColor.release();}catch(Exception e){}
            try{text_WackyColor.release();}catch(Exception e){}
            try{text_Desktop01.release();}catch(Exception e){}
            try{text_Desktop02.release();}catch(Exception e){}
            try{text_Desktop03.release();}catch(Exception e){}
            try{text_Unlock01.release();}catch(Exception e){}
            try{text_Unlock02.release();}catch(Exception e){}
            try{text_Unlock03.release();}catch(Exception e){}
            try{BuildModeLayout.release();}catch(Exception e){}
            try{UnPackingModeLayout.release();}catch(Exception e){}
            try{SourceSelector.release();}catch(Exception e){}
            try{text_DesiredColor.release();}catch(Exception e){}
            try{textBox_LuckySymbol.release();}catch(Exception e){}
            try{BalanceSlider.release();}catch(Exception e){}
            try{switch_CrazyMode.release();}catch(Exception e){}
            try{switch_IColorEngine.release();}catch(Exception e){}
            try{textBox_UnpackingResults.release();}catch(Exception e){}
            setBg01 = null;
            setBg02 = null;
            setBg03 = null;
            pxm = null;
            textBox_ChineseName = null;
            textBox_InternationalName = null;
            textBox_DesignerName = null;
            textBox_VersionCode = null;
            textBox_BriefInfo = null;
            text_ChineseName = null;
            text_InternationalName = null;
            text_DesignerName = null;
            text_VersionCode = null;
            Dialog_Title = null;
            Dialog_Content_StoragePermissionFailed = null;
            Dialog_Button_Cancel = null;
            Dialog_Button_Confirm = null;
            Toast_NoneName = null;
            Toast_NoneDesigner = null;
            Toast_NoneVersion = null;
            Toast_NoneBriefInfo = null;
            Toast_NoneBackgrounds = null;
            Toast_IsProcessing = null;
            Toast_Theme_SaveFinish = null;
            Toast_Theme_SaveFailed = null;
            Toast_BlindBox_IsProcessing = null;
            Toast_BlindBox_SaveFinish = null;
            Toast_BlindBox_SaveFailed = null;
            mainThreadEventHandler = null;
            PacThemeEventHandler = null;
            screenEventHandler = null;
            popupDialogDelayEventHandler = null;
            text_LuckyColor = null;
            text_NormalColor = null;
            text_WackyColor = null;
            text_Desktop01 = null;
            text_Desktop02 = null;
            text_Desktop03 = null;
            text_Unlock01 = null;
            text_Unlock02 = null;
            text_Unlock03 = null;
            LuckyColor = null;
            NormalColor = null;
            WackyColor = null;
            Color01 = null;
            Color02 = null;
            Color03 = null;
            Color04 = null;
            Color05 = null;
            Color06 = null;
            Color07 = null;
            Color08 = null;
            Color09 = null;
            Color10 = null;
            Color11 = null;
            Color12 = null;
            Color13 = null;
            Color14 = null;
            Color15 = null;
            Color16 = null;
            Color17 = null;
            Color18 = null;
            Color19 = null;
            BuildModeLayout = null;
            UnPackingModeLayout = null;
            SourceSelector = null;
            text_DesiredColor = null;
            textBox_LuckySymbol = null;
            BalanceSlider = null;
            switch_CrazyMode = null;
            switch_IColorEngine = null;
            textBox_UnpackingResults = null;
            DesiredColor = null;
            timeStr = null;
            System.gc();
            if(ThemesEditorAbility.LayoutChanged)
            {
                ThemesEditorAbility.LayoutChanged = false;
                try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
            }
            else
            {
                try{MainSceneSlice.Instance.pageSwiper.ReturnImageSwiper_Industry(true);}catch (Exception ex){}
            }
            super.onBackPressed();
        }else
        {
            new GeneralToast(this).setText(isUnpackMode?Toast_IsProcessing:Toast_BlindBox_IsProcessing).show();
        }
    }

    private void onChangeMode()
    {
        if(!isUnpackMode)
        {
            if(!isProcessing)
            {
                textBox_ChineseName.clearFocus();
                textBox_InternationalName.clearFocus();
                textBox_DesignerName.clearFocus();
                textBox_VersionCode.clearFocus();
                textBox_BriefInfo.clearFocus();
                textBox_LuckySymbol.clearFocus();
                UnPackingModeLayout.setVisibility(Component.VISIBLE);
                BuildModeLayout.setVisibility(Component.HIDE);
                ((Text)findComponentById(ResourceTable.Id_BlindBox_title)).setText(ResourceTool.getString(this,ResourceTable.String_BlindBox_Title_UnPacMode,"开启盲盒"));
                isUnpackMode = true;
                DatabaseManager.Init(this);
                DatabaseManager.setString("ThemesBlindBox_ModeValue","Unpack");
            }else
                new GeneralToast(this).setText(Toast_BlindBox_IsProcessing).show();
        }else
        {
            if(!isProcessing)
            {
                textBox_LuckySymbol.clearFocus();
                textBox_ChineseName.clearFocus();
                textBox_InternationalName.clearFocus();
                textBox_DesignerName.clearFocus();
                textBox_VersionCode.clearFocus();
                textBox_BriefInfo.clearFocus();
                BuildModeLayout.setVisibility(Component.VISIBLE);
                UnPackingModeLayout.setVisibility(Component.HIDE);
                ((Text)findComponentById(ResourceTable.Id_BlindBox_title)).setText(ResourceTool.getString(this,ResourceTable.String_BlindBox_Title_BuildMode,"制作盲盒"));
                isUnpackMode = false;
                DatabaseManager.Init(this);
                DatabaseManager.setString("ThemesBlindBox_ModeValue","Build");
            }else
                new GeneralToast(this).setText(Toast_IsProcessing).show();
        }
    }

    private void showDialog_Popup_SwitchMode(Component c)
    {
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
        popupDialog = new PopupDialog(getContext(), c);
        DirectionalLayout directionalLayout = new DirectionalLayout(getContext());
        directionalLayout.setHeight(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        directionalLayout.setWidth(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        directionalLayout.setPadding((int)((15f*displayAttributes.scalDensity)+0.5f),(int)((8f*displayAttributes.scalDensity)+0.5f),(int)((15f*displayAttributes.scalDensity)+0.5f),(int)((8f*displayAttributes.scalDensity)+0.5f));
        directionalLayout.setAlignment(LayoutAlignment.CENTER);
        directionalLayout.setBackground(new ShapeElement(){{setRgbColor(RgbColor.fromArgbInt(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_popup_dialog_bg,0xDADADA)));setCornerRadius((int)((6f*displayAttributes.scalDensity)+0.5f));}});
        Text text = new Text(getContext());
        text.setHeight(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        text.setWidth(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        text.setTextSize(AttrHelper.fp2px(14,getContext()));
        text.setTextColor(new Color(ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_popup_dialog_text,0x151515)));
        text.setText(ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_SwitchMode,"切换模式"));
        directionalLayout.addComponent(text);
        popupDialog.setCustomComponent(directionalLayout);
        popupDialog.setMode(LayoutAlignment.BOTTOM|LayoutAlignment.RIGHT);
        popupDialog.setTransparent(true);
        popupDialog.setCornerRadius((int)((8f*displayAttributes.scalDensity)+0.5f));
        popupDialog.setAutoClosable(true);
        //此项能力会导致应用程序在特定场景闪退，暂不使用！
        //popupDialog.setDuration(3000);
        popupDialog.show();
        popupDialogDelayEventHandler.removeAllEvent();
        popupDialogDelayEventHandler.sendEvent(0, 3000, EventHandler.Priority.IMMEDIATE);
    }

    private CommonDialog.DestroyedListener colorSelectorListener()
    {
        return () ->
        {
            try
            {
                DatabaseManager.Init(this);
                //不直接采用数组模式是有原因的，请代码阅读者自行体会！
                if(iNum == -1)
                {
                    DesiredColor = ColorManager.getColorHex(colorDialog.getColorValue());
                    text_DesiredColor.setText("#"+DesiredColor);
                    DatabaseManager.setString("ThemesBlindBox_DesiredColor",DesiredColor);
                }
                else if(iNum == 1)
                {
                    LuckyColor = ColorManager.getColorHex(colorDialog.getColorValue());
                    text_LuckyColor.setText("#"+LuckyColor);
                    DatabaseManager.setString("ThemesBlindBox_LuckyColor",LuckyColor);
                }else if(iNum == 2)
                {
                    NormalColor = ColorManager.getColorHex(colorDialog.getColorValue());
                    text_NormalColor.setText("#"+NormalColor);
                    DatabaseManager.setString("ThemesBlindBox_NormalColor",NormalColor);
                }else if(iNum == 3)
                {
                    WackyColor = ColorManager.getColorHex(colorDialog.getColorValue());
                    text_WackyColor.setText("#"+WackyColor);
                    DatabaseManager.setString("ThemesBlindBox_WackyColor",WackyColor);
                }
            }catch (Exception ex){}
        };
    }

    private void showDialog_ColorSelector()
    {
        String iColorStr = "#FFFFFF";
        //不直接采用数组模式是有原因的，请代码阅读者自行体会！
        if(iNum==-1)
            iColorStr = text_DesiredColor.getText();
        else if(iNum==1)
            iColorStr = text_LuckyColor.getText();
        else if(iNum==2)
            iColorStr = text_NormalColor.getText();
        else if(iNum==3)
            iColorStr = text_WackyColor.getText();
        colorDialog = new ColorDialog(this);
        colorDialog.setDestroyedListener(colorSelectorListener());
        colorDialog
                .setTitle(ResourceTool.getString(this,ResourceTable.String_Dialog_SelectorColor,"选择颜色"))
                .setCloseText(ResourceTool.getString(this,ResourceTable.String_Dialog_text_close,"关闭"))
                .setDefaultColor(iColorStr)
                .setOutsideTouchClosable(false)
                .show();
    }

    private void recoverDialog_ColorSelector()
    {
        DatabaseManager.Init(getContext());
        colorDialog = new ColorDialog(this);
        colorDialog.setDestroyedListener(colorSelectorListener());
        colorDialog
                .setTitle(ResourceTool.getString(this,ResourceTable.String_Dialog_SelectorColor,"选择颜色"))
                .setCloseText(ResourceTool.getString(this,ResourceTable.String_Dialog_text_close,"关闭"))
                .setDefaultColor(DatabaseManager.getInt("ColorDialog_TempColorValue",-1))
                .setOutsideTouchClosable(false)
                .show();
    }

    public void PermissionRouter(GeneralDialog dialog)
    {
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
                .withUri(Uri.getUriFromParts("package",getBundleName(),null))
                .build();
        e.setOperation(operation);
        startAbility(e);
        dialog.remove();
    }

    private void showPermissionRequest()
    {
        if (canRequestPermission("ohos.permission.READ_USER_STORAGE") && canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
            requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_USER_STORAGE"}, 2);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(Dialog_Content_StoragePermissionFailed)
                    .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }

    private void showShareFaRequest(String text)
    {
        if (canRequestPermission("ohos.permission.READ_USER_STORAGE") && canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
            requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_USER_STORAGE"}, 2);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(text)
                    .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::ShareFA)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }

    private void updateColors()
    {
        try
        {
            ColorManager.HsvBox hsvBox = ColorManager.getHsvBox(Color.getIntColor("#"+Color04));
            float H = hsvBox.getHue();
            float S = hsvBox.getSaturation();
            float V = hsvBox.getValue();
            Color01 = ColorManager.getColorHex(HsvColor.toColor(255,H, 28f, 100f));
            Color02 = ColorManager.getColorHex(HsvColor.toColor(255,H,12f, 99f));
            Color03 = ColorManager.getColorHex(HsvColor.toColor(255,H,25f, 96f));
            Color05 = ColorManager.getColorHex(HsvColor.toColor(255,H, (100f-S)*0.8f, 100f));
            Color06 = ColorManager.getColorHex(HsvColor.toColor(255,H, 36f, 60f));
            Color07 = Color04;
            Color08 = ColorManager.getColorHex(HsvColor.toColor(255,H,18f, 99f));
            Color09 = ColorManager.getColorHex(HsvColor.toColor(255,H, 5f, 100f));
            Color10 = ColorManager.getColorHex(HsvColor.toColor(255,H, 4f, 96f));
            Color11 = ColorManager.getColorHex(HsvColor.toColor(255,H, S, V*0.92f));
            Color12 = ColorManager.getColorHex(HsvColor.toColor(255,H, 4f, 100f));
            Color13 = ColorManager.getColorHex(HsvColor.toColor(255,H, S, V*0.9f));
            Color14 = ColorManager.getColorHex(HsvColor.toColor(255,H, 8f, 100f));
            Color15 = ColorManager.getColorHex(HsvColor.toColor(255,H, 16f,99f));
            Color16 = ColorManager.getColorHex(HsvColor.toColor(255,H, 6f, 100f));
            Color17 = ColorManager.getColorHex(HsvColor.toColor(255,H, 15f, 99f));
            Color18 = ColorManager.getColorHex(HsvColor.toColor(255,H, 17f, 100f));
            Color19 = ColorManager.getColorHex(HsvColor.toColor(255,H, 46f,89f));
        }catch (Exception e){}
    }

    private void updateXmlColorValue(String fileName)
    {
        File xmlFile = new File(fileName);
        try
        {
            FileInputStream in = new FileInputStream(xmlFile);
            byte[] b = new byte[(int) xmlFile.length()];
            in.read(b);
            String xmlText = new String(b);
            in.close();
            DatabaseManager.Init(getContext());
            xmlText = xmlText.replaceAll("\\*【01】旧版顶部栏配色\\*",Color01);
            xmlText = xmlText.replaceAll("\\*【02】导航栏配色\\*",Color02);
            xmlText = xmlText.replaceAll("\\*【03】中等深度标签普通配色\\*",Color03);
            xmlText = xmlText.replaceAll("\\*【04】主题核心配色\\*", Color04);
            xmlText = xmlText.replaceAll("\\*【05】主要浅色高亮配色\\*",Color05);
            xmlText = xmlText.replaceAll("\\*【06】搜索框文字配色\\*",Color06);
            xmlText = xmlText.replaceAll("\\*【07】主要顶部图示配色\\*",Color07);
            xmlText = xmlText.replaceAll("\\*【08】柔浅小贴士背景\\*",Color08);
            xmlText = xmlText.replaceAll("\\*【09】圆形按钮底色\\*",Color09);
            xmlText = xmlText.replaceAll("\\*【10】圆形按钮按压色\\*",Color10);
            xmlText = xmlText.replaceAll("\\*【11】圆形按钮图示色\\*",Color11);
            xmlText = xmlText.replaceAll("\\*【12】开关栏背景配色(含透明度)\\*",Color12);
            xmlText = xmlText.replaceAll("\\*【13】主用较深按压色\\*",Color13);
            xmlText = xmlText.replaceAll("\\*【14】对话框底板配色\\*",Color14);
            xmlText = xmlText.replaceAll("\\*【15】拨号器键盘底色\\*",Color15);
            xmlText = xmlText.replaceAll("\\*【16】程式背景浅底色\\*",Color16);
            xmlText = xmlText.replaceAll("\\*【17】邮件搜索框及侧边色\\*",Color17);
            xmlText = xmlText.replaceAll("\\*【18】短信顶部底部配色\\*",Color18);
            xmlText = xmlText.replaceAll("\\*【19】旧版状态栏开关色\\*",Color19);
            FileOutputStream out = null;
            try
            {
                out = new FileOutputStream(xmlFile);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                writer.write(xmlText);
                writer.close();
                out.flush();
                out.close();
            }catch(IOException ex){ex.printStackTrace();}
            finally
            {
                try
                {
                    if (out != null)
                    {
                        out.close();
                    }
                } catch(IOException e){}
            }
        }catch(IOException ex) {}
    }

    private void updateXmlRadiusValue(String fileName,int mValue)
    {
        File xmlFile = new File(fileName);
        try
        {
            FileInputStream in = new FileInputStream(xmlFile);
            byte[] b = new byte[(int) xmlFile.length()];
            in.read(b);
            String xmlText = new String(b);
            in.close();
            DatabaseManager.Init(getContext());
            xmlText = xmlText.replaceAll("16dp",mValue+"dp");
            FileOutputStream out = null;
            try
            {
                out = new FileOutputStream(xmlFile);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                writer.write(xmlText);
                writer.close();
                out.flush();
                out.close();
            }catch(IOException ex){ex.printStackTrace();}
            finally
            {
                try
                {
                    if (out != null)
                    {
                        out.close();
                    }
                } catch(IOException e){}
            }
        }catch(IOException ex) {}
    }

    private void selectPic(int fileMode,int num)
    {
        iNum = num;
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType("image/*");
        startAbilityForResult(intent,fileMode);
    }

    private void selectBlindBox()
    {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType("*/*");
        startAbilityForResult(intent,ChooseThemesBlindBox);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData)
    {
        if(requestCode==ChooseThemesBlindBox)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String FileUri=resultData.getUriString();
                Uri targetUri;
                if(!FileUri.endsWith(".tbb")&&FileUri.contains("externalstorage"))
                    new GeneralToast(this).setText(ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_InvalidFile,"请选择有效的盲盒文件！")).show();
                else
                {
                    targetUri = resultData.getUri();
                    DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                    try
                    {
                        InputStream inputStream = null;
                        OutputStream outputStream = null;
                        try
                        {
                            inputStream = new FileInputStream(dataAbilityHelper.openFile(targetUri, "r"));
                            outputStream = new FileOutputStream(getCacheDir()+"/dawnlighti_target_blindbox.tbb");
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length=inputStream.read(buffer))>0)
                            {
                                outputStream.write(buffer,0,length);
                            }
                            outputStream.flush();
                            outputStream.close();
                        }finally
                        {
                            try
                            {
                                if (outputStream != null)
                                    outputStream.close();
                                if(inputStream != null)
                                    inputStream.close();
                            } catch(IOException e){}
                        }
                        int VersionNum = GeneralUtil.readBlindBoxVersion(getCacheDir()+"/dawnlighti_target_blindbox.tbb",getContext());
                        if(VersionNum!=-1&&VersionNum<=BlindBoxVersion)
                        {
                            DatabaseManager.Init(this);
                            DatabaseManager.setString("ThemesBlindBoxAbility_ThemesBlindBoxUri", FileUri);
                            SourceSelector.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        }
                        else if(VersionNum>BlindBoxVersion)
                        {
                            FileManager.delete(getCacheDir()+"/dawnlighti_target_blindbox.tbb");
                            new GeneralToast(this).setText(ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_VersionTooLow,"盲盒版本高于客户端版本！")).show();
                        }
                        else
                        {
                            FileManager.delete(getCacheDir()+"/dawnlighti_target_blindbox.tbb");
                            new GeneralToast(this).setText(ResourceTool.getString(getContext(),ResourceTable.String_BlindBox_FileDamaged,"盲盒文件已损坏，请重新选择！")).show();
                        }
                    } catch (Exception e) {}
                }
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Background)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Background0"+iNum, ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Background0"+iNum,targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    String workPath = getCacheDir() + "/ThemesBlindBox";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(workPath+"/Background0"+iNum+".jpg",pixelMap);
                    if(new File(workPath+"/Background0"+iNum+".jpg").exists())
                    {
                        //不直接采用数组模式是有原因的，请代码阅读者自行体会！
                        if(iNum == 1)
                        {
                            setBg01.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                            setBg01.setPixelMap(pixelMap);
                        }
                        else if(iNum == 2)
                        {
                            setBg02.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                            setBg02.setPixelMap(pixelMap);
                        }
                        else if(iNum == 3)
                        {
                            setBg03.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                            setBg03.setPixelMap(pixelMap);
                        }
                        if(ImageIntelligent.isDarkImage(pixelMap))
                            new GeneralToast(getContext()).setText(ResourceTool.getString(getContext(),ResourceTable.String_IToast_BackgroundTooDark,"智慧助手：请注意，侦测到所选图片的色彩较为暗淡，以此作为程序背景，或将严重破坏主题的体验效果！")).show();
                    }
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Desktop)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Desktop0"+iNum, ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Desktop0"+iNum,targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    String workPath = getCacheDir() + "/ThemesBlindBox";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(workPath+"/Desktop0"+iNum+".jpg",pixelMap);
                    if(new File(workPath+"/Desktop0"+iNum+".jpg").exists())
                    {
                        //不直接采用数组模式是有原因的，请代码阅读者自行体会！
                        if(iNum == 1)
                            text_Desktop01.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(iNum == 2)
                            text_Desktop02.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(iNum == 3)
                            text_Desktop03.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                    }
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }else if(requestCode==ChooseImage_Unlock)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Unlock0"+iNum, ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("ThemesBlindBoxAbility_ImageUri_Unlock0"+iNum,targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    String workPath = getCacheDir() + "/ThemesBlindBox";
                    if(!new File(workPath).exists())new File(workPath).mkdirs();
                    ImageIntelligent.saveImage(workPath+"/Unlock0"+iNum+".jpg",pixelMap);
                    if(new File(workPath+"/Unlock0"+iNum+".jpg").exists())
                    {
                        //不直接采用数组模式是有原因的，请代码阅读者自行体会！
                        if(iNum == 1)
                            text_Unlock01.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(iNum == 2)
                            text_Unlock02.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));
                        else if(iNum == 3)
                            text_Unlock03.setText(ResourceTool.getString(getContext(),ResourceTable.String_SimpleInfo_ImageModified,"*已设置"));                    }
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }
    }

    public void ShareFA(GeneralDialog dialog)
    {
        PacMapEx pacMap = new PacMapEx();
        pacMap.putObjectValue(ShareFaManager.SHARING_FA_TYPE, 0);
        pacMap.putObjectValue(ShareFaManager.HM_BUNDLE_NAME, getBundleName());
        pacMap.putObjectValue(ShareFaManager.SHARING_EXTRA_INFO, "ShareFa_BlindBox");
        pacMap.putObjectValue(ShareFaManager.HM_ABILITY_NAME, ThemesEditorAbility.class.getName());
        pacMap.putObjectValue(ShareFaManager.SHARING_CONTENT_INFO, "「"+ResourceTool.getString(getContext(),ResourceTable.String_Special_ThemesBlindBox,"主题盲盒")+"」"+textBox_InternationalName.getText()+".tbb");
        pacMap.putObjectValue(ShareFaManager.SHARING_THUMB_DATA, GeneralUtil.getResourceByte(getContext(),ResourceTable.Media_ShareFa_BlindBox));
        pacMap.putObjectValue(ShareFaManager.HM_FA_ICON, GeneralUtil.getResourceByte(getContext(),ResourceTable.Media_ApplicationIcon));
        pacMap.putObjectValue(ShareFaManager.HM_FA_NAME, ResourceTool.getString(getContext(),ResourceTable.String_ApplicationName,"主题协作器"));
        dialog.remove();
        // 第一个参数为appid，在华为AGC创建原子化服务时自动生成。
        ShareFaManager.getInstance(ThemesBlindBoxSlice.this).shareFaInfo(GeneralUtil.appId, pacMap);
    }
    @Override
    public void onActive() {super.onActive();}

    @Override
    public void onForeground(Intent intent) {super.onForeground(intent);}
}